from backend.common import register_docs, register_static_file
from fastapi import FastAPI
from backend.config.config import settings
from backend.middleware.cors import register_cors_middleware
from backend.api.urls import register_routers
from contextlib import asynccontextmanager
from backend.common.database import db_lifespan
from backend.common.cache import redis_lifespan
from backend.middleware.http_timing import register_http_timing_middleware  
from backend.middleware.request_log import register_request_log_middleware
from backend.services.user_service import DepartmentService  # 导入DepartmentService
from backend.common.logging import logger
from backend.common.minio import get_minio_client  # 导入get_minio_client


@asynccontextmanager
async def lifespan(app: FastAPI):
    # 初始化数据库连接
    async with db_lifespan(app):
        # 初始化Redis连接
        async with redis_lifespan(app):
            # 初始化部门树缓存
            await init_department_tree_cache()
            # 初始化MinIO存储桶
            init_minio_bucket()
            
            yield




# 初始化部门树缓存
async def init_department_tree_cache():
    try:
        # 初始化部门树缓存
        success = await DepartmentService.initialize_department_tree_cache()
        if success:
            logger.info("✅ 部门树缓存已初始化")
        else:
            logger.error("❌ 部门树缓存初始化失败")
    except Exception as e:
        logger.error(f"❌ 部门树缓存初始化发生异常: {str(e)}")

# 初始化MinIO存储桶
def init_minio_bucket():
    try:
        # 创建MinioClient实例时会自动检查并创建存储桶
        minio_client = get_minio_client()
        logger.info(f"✅ MinIO存储桶 {minio_client.bucket_name} 已初始化")
    except Exception as e:
        logger.error(f"❌ MinIO存储桶初始化发生异常: {str(e)}")


app = FastAPI(
    title=settings.DESC,
    description="RPA API 服务，集成了任务调度、WebSocket 通信等功能",
    version=settings.VERSION,
    docs_url=None,
    redoc_url=None,
    lifespan=lifespan
)
# 初始化静态文件
register_static_file(app)

# 使用本地docs静态文件
register_docs(app)

# 注册跨域中间件
register_cors_middleware(app)

# 注册http timing中间件
register_http_timing_middleware(app)

# 注册路由
register_routers(app)

# 注册请求日志中间件
register_request_log_middleware(app)







if __name__ == "__main__":
    import uvicorn

    uvicorn.run(
        "backend.main:app",
        host="0.0.0.0",
        port=5000
    )